package com.duoduo.admin.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.duoduo.common.core.constant.CacheConstants;
import com.duoduo.common.core.constant.enums.DictTypeEnum;
import com.duoduo.common.core.exception.ErrorCodes;
import com.duoduo.common.core.util.MsgUtils;
import com.duoduo.common.core.util.R;
import com.duoduo.common.jpa.service.CommonService;

import io.swagger.v3.oas.annotations.media.Schema;

import com.duoduo.admin.api.dto.SysDictDTO;
import com.duoduo.admin.entity.SysDict;
import com.duoduo.admin.entity.SysDictItem;
import com.duoduo.admin.repository.SysDictItemRepository;
import com.duoduo.admin.repository.SysDictRepository;

import jakarta.persistence.criteria.Predicate;

/**
 * 字典表
 * @author mason
 *
 */
@Service
public class SysDictService extends CommonService<SysDictDTO, SysDict, Long>{

	@Autowired
	private SysDictRepository sysDictRepository;
	@Autowired
	private SysDictItemRepository sysDictItemRepository;

	@Override
	public Specification<SysDict> getWhere(final SysDictDTO request) {
		return (root, query, cb) -> {
			final List<Predicate> predicate = new ArrayList<Predicate>();
			if(request.getId()!=null) {
				predicate.add(cb.equal(root.get("id"), request.getId()));	
			}		
			
			final Predicate[] pre = new Predicate[predicate.size()];
			return query.where(predicate.toArray(pre)).getRestriction();
		};
	}

	/**
	 * 根据ID 删除字典
	 * @param id 字典ID
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
	public void removeDict(Long id) {
		SysDict dict =sysDictRepository.findById(id).orElseThrow();
		// 系统内置
		Assert.state(!DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag()),
				MsgUtils.getMessage(ErrorCodes.SYS_DICT_DELETE_SYSTEM));
		sysDictRepository.delete(dict);
	}
	/**
	 * 更新字典
	 * @param dict 字典
	 * @return
	 */
	@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#dict.type")
	public void updateDict(SysDictDTO dict) {
		SysDict sysDict = sysDictRepository.findById(dict.getId()).orElseThrow();
		// 系统内置
		Assert.state(!DictTypeEnum.SYSTEM.getType().equals(sysDict.getSystemFlag()),
				MsgUtils.getMessage(ErrorCodes.SYS_DICT_UPDATE_SYSTEM));
		BeanUtils.copyProperties(dict, sysDict,"createBy","createTime","updateBy","updateTime");
		sysDictRepository.save(sysDict);
	}

	@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
	public void clearDictCache() {

	}

	public R<List<SysDictItem>> getDictByKey(String key) {
		// TODO Auto-generated method stub
		return null;
	}

}
